<template>
  <div class="user-manager">
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" @close="resetDialog" append-to-body>
      <!--  <div class="mb-4">
          <el-input v-model="searchQuery" placeholder="请输入用户名搜索" size="small"
                    style="width: 200px" @keyup.enter.native="fetchUsers">
            <el-button slot="append" icon="el-icon-search" @click="fetchUsers"></el-button>
          </el-input>
        </div> -->

      <el-table :data="userList" stripe highlight-current-row>
        <el-table-column prop="username" label="用户名" width="150"></el-table-column>
        <el-table-column prop="nickname" label="昵称" width="150"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="150"></el-table-column>
        <el-table-column prop="userRoleName" label="角色" width="150">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isAdmin==true?'warning':''">{{ scope.row.isAdmin==true?'管理员':'普通用户' }}</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="remark" label="备注"></el-table-column> -->
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="warning" @click="handleEditUser(scope.row)">
              <i class="fa fa-edit mr-1"></i>编辑
            </el-button>
            <el-button size="mini" type="danger" @click="handleDeleteUser(scope.row)">
              <i class="fa fa-trash mr-1"></i>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="flex justify-between items-center mt-4" style="margin: 15px 0;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleCreateUser" icon="el-icon-plus">
          新增用户
        </el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog :title="userFormTitle" :visible.sync="userFormVisible" width="500px" append-to-body>
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="formData.nickname"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="formData.password" type="password" v-show="reset || userFormTitle=='新增用户'"></el-input>
          <el-button  type="text" v-show="!reset && userFormTitle!='新增用户'" @click="reset=true" size="mini">重置密码</el-button>
        </el-form-item>
        <el-form-item label="角色" prop="isAdmin">
          <!-- :disabled="formData.isAdmin == 1 ? false : true" -->
          <el-select v-model="formData.isAdmin" placeholder="请选择角色" @change="changeRoles">
            <el-option v-for="item in roleOptions" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="知识库审核" v-if="formData.isAdmin">
          <el-radio-group v-model="formData.kdAuditRole">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      <!--  <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="4"></el-input>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button @click="userFormVisible = false">取消</el-button> -->
        <el-button @click="handleCancelUser">取消</el-button>
        <el-button type="primary" @click="handleSaveUser">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import moment from 'moment';
  import 'moment/locale/zh-cn'
  import CryptoJS from 'crypto-js';
  export default {
    name: 'UserManager',
    props: {
      api: {
        type: Object,
        required: false
      }
    },
    data() {
      return {
        reset: false,
        dialogVisible: false,
        dialogTitle: '用户管理',

        userList: [],
        total: 0,
        currentPage: 1,
        pageSize: 10,
        searchQuery: '',

        userFormVisible: false,
        userFormTitle: '新增用户',
        formData: {
          "id": "",
          "username": "",
          "nickname": "",
          "password": "",
          "phone": "",
          "email": "",
          "status": true,
          "roleId": 1,
          "remark":'',
          "isAdmin":'',
          "kdAuditRole": 0,
        },
        rules: {
          username: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 20,
              message: '用户名长度在2-20个字符',
              trigger: 'blur'
            }
          ],
          nickname: [{
              required: true,
              message: '请输入用户昵称',
              trigger: 'blur'
            }
          ],
          phone: [{
              required: true,
              message: '请输入手机号',
              trigger: 'blur'
            },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: '请输入正确的手机号',
              trigger: 'blur'
            }
          ],
          password: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 20,
              message: '密码长度在6-20个字符',
              trigger: 'blur'
            }
          ],
          role: [{
            required: true,
            message: '请选择角色',
            trigger: 'change'
          }]
        },

        deleteDialogVisible: false,
        deleteUserId: null,
        deleteUserName: '',

        roleOptions: [{
            label: '管理员',
            value: 1
          },
          {
            label: '普通用户',
            value: 0
          },
        ]
      };
    },
    methods: {
      open() {
        this.dialogVisible = true;
        this.fetchUsers();
        this.$nextTick(()=>{
          this.reset= false;
        })
      },
      changeRoles(value) {
        console.log(value)
        // if(value == 1) {
        //   this.formData.isAdmin = 1
        // }
        this.formData.isAdmin = value
      },

      resetDialog() {
        this.searchQuery = '';
        this.currentPage = 1;
      },

      // 获取用户列表
      fetchUsers() {
        let parms = {
          pageIndex: this.currentPage,
          pageSize: this.pageSize,
          query: this.searchQuery
        }
        this.$httpApi.getUserPage(parms).then((res) => {
          if (res.success) {
            this.userList = res.data.list;
            this.total = res.data.total;
          } else {
            this.$message.error(res.msg);
          }
        });
      },

      // 处理分页大小变化
      handleSizeChange(newSize) {
        this.pageSize = newSize;
        this.fetchUsers();
      },

      // 处理当前页变化
      handleCurrentChange(newPage) {
        this.currentPage = newPage;
        this.fetchUsers();
      },

      // 处理创建用户
      handleCreateUser() {
        this.userFormTitle = '新增用户';
        this.formData = {
            "id": "",
            "username": "",
            "nickname": "",
            "password": "",
            "phone": "",
            "email": "",
            "status": true,
            "roleId": 1,
            "remark":'',
            "kdAuditRole": 0
        };
        this.userFormVisible = true;
      },

      // 处理编辑用户
      handleEditUser(user) {
        this.userFormTitle = '编辑用户';
        this.formData = user;
        this.formData.isAdmin=user.isAdmin==true?1:0
        this.formData.kdAuditRole=user.kdAuditRole==true?1:0
        console.log(user)
        // 编辑时不要求输入密码
        this.$refs.formRef && this.$refs.formRef.clearValidate('password');
        this.userFormVisible = true;
         this.reset= false;
      },

      // 处理取消
      handleCancelUser() {
        // this.$refs.formRef.resetFields()
        this.fetchUsers()
        this.userFormVisible = false
      },

      // 处理保存用户
      handleSaveUser() {
        this.$refs.formRef.validate(async (valid) => {
          if (!valid) return;
          try {
            let res;
          if(this.formData.id){
            let parms = this.formData
            // parms.password=this.$AesEncrypt(parms.password)
            this.$httpApi.updateSysUser(parms).then((res) => {
              if (res.success) {
                  this.$message.success('操作成功');
                this.fetchUsers();
                this.userFormVisible = false;
              } else {
                this.$message.error(res.msg);
              }
            });
          }else{
            let parms = this.formData
            // parms.password=this.$AesEncrypt(parms.password)
            this.$httpApi.addSysUser(parms).then((res) => {
              if (res.success) {
                 this.$message.success('操作成功');
                this.fetchUsers();
                this.userFormVisible = false;
              } else {
                this.$message.error(res.msg);
              }
            });
          }

          } catch (error) {
            this.$message.error('操作失败');
            console.error(error);
          }
        });
      },
      // 处理删除用户
      handleDeleteUser(user) {
        this.deleteUserId = user;
        this.$confirm('确认要删除该用户吗？', '提示信息', {
            distinguishCancelAndClose: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          })
          .then(() => {
            // 执行保存相关操作
            this.handleConfirmDelete(user)
          })
          .catch(action => {
            if (action === 'cancel') {
              // 执行打印相关操作
            } else {
              // 关闭图标触发
            }
          });
      },
      // 处理确认删除
      handleConfirmDelete(user) {
        let parms = user
        this.$httpApi.deleteUser(parms).then((res) => {
          if (res.success) {
            this.$message.success('操作成功！');
            this.fetchUsers();
            this.deleteDialogVisible = false;
          } else {
            this.$message.error(res.msg);
          }
        });
      },

      // 获取角色标签类型
      getRoleType(role) {
        const roleTypes = {
          '管理员': '管理员',
          '编辑': 'warning',
          '普通用户': '普通用户',
          '访客': 'info',
          '测试': 'success'
        };
        return roleTypes[role] || '普通用户';
      },

      // 格式化日期
      formatDate(dateStr) {
        return dateStr ? dateStr.split('.')[0] : '';
      }
    }
  }
</script>

<style scoped>
  .user-manager {
    padding: 16px;
  }
</style>
